<template>
  <div class="components-layout-demo">
    <!--访客预约天数配置-->
    <a-layout style="height:100%">
      <a-layout style="background: #fff;height:100%">
        <!--<a-layout-sider class="layout-sider-left">-->
          <!--<div style="height:100%;">-->
            <!--<sidebar-role-->
              <!--ref="roleMainTree"-->
              <!--:checkable="false"-->
              <!--@on-select="roleMainTreeSelect"-->
            <!--&gt;</sidebar-role>-->
          <!--</div>-->
        <!--</a-layout-sider>-->
        <a-layout-content class="layoutContent">
          <div class="components-table-demo-size" style="height:100%">
            <!-- tools盒子 每个页面必须存在的div盒子，除了表格以外的功能都放在这个里面 -->
            <div id="tools">
              <div class="height8"></div>
              <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">
                <!--<a-form-item label="关键字" class="marginBtm">-->
                  <!--<a-input v-model="query.searchName"-->
                           <!--allowClear placeholder="请输入用户名/姓名查询"-->
                           <!--class="marginBtm"-->
                  <!--/>-->
                <!--</a-form-item>-->
                <a-form-item label="基地" style="margin-top: -2px;">
                  <a-dropdown class="min-width-110">
                    <a-menu slot="overlay" @click="baseMenuClick">
                      <a-menu-item :key="item.id" v-for="item in baceType">{{item.name}}</a-menu-item>
                    </a-menu>
                    <a-button>
                      <div class="query-conditions">
                        {{ visitBaseName }}
                        <a-icon type="down"/>
                      </div>
                    </a-button>
                  </a-dropdown>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="searching">
                    查询
                  </a-button>
                </a-form-item>

                <a-form-item>
                  <a-button type="primary" @click="openModal('新增')">
                    新增
                  </a-button>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="openModal('修改')">
                    修改
                  </a-button>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="dateleUser">
                    删除
                  </a-button>
                </a-form-item>

              </a-form>

              <a-divider style="margin: 5px 0 8px 0"/>

            </div>
            <!-- 右侧数据表格  :row-selection="rowSelection"-->
            <a-spin :spinning="spinning" tip="删除中...">
              <div id="tableBox" class="tableOthStyle">
                <a-table
                  ref="mainTable"
                  bordered
                  class="a-table"
                  size="small"
                  :columns="columns"
                  :dataSource="tableData"
                  :loading="loading"
                  :rowKey="(record) => record.id"
                  :pagination="pagination"
                  :scroll="{ y: yHeight,x:xWidth}"
                  :locale="localezh_CN"
                  :row-selection="rowSelection"
                  :customRow="selectRow"
                  :rowClassName="setRowClassName"
                ></a-table>
              </div>
            </a-spin>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- 模态框 -->
    <a-modal
      :destroyOnClose="true"
      :maskClosable="false"
      :keyboard="false"
      @ok="addAccountOk"
      @cancel="addAccountCancel"
      v-model="modalVisible"
      :title="modalTitle"
      width="400px"
      :bodyStyle="{padding: '20px'}"
      :okText="'保存'"
      :confirmLoading="confirmLoading"
    >
      <a-spin :spinning="modalLoading">
        <!--自定义宽度三列模板-->
        <a-descriptions bordered size="small" :column="3">
          <a-descriptions-item :span="3">
            <template v-slot:label>
              <div class="contShortwidth">基地</div>
            </template>
            <div class="contwidthLon">
              <a-select placeholder="请选择基地" showArrow v-model="modalParams.baseId"
                        style="width: 100%" @change="handleChangeBase">
                <a-select-option v-for="item in baceTypeModal" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </div>
          </a-descriptions-item>
          <a-descriptions-item :span="3">
            <template v-slot:label>
              <div class="contShortwidth">区域</div>
            </template>
            <div class="contwidthLon">
              <a-select placeholder="请选择区域" showArrow v-model="modalParams.areaId"
                        style="width: 100%" @change="handleChangeArea" :disabled="modalParams.noarea">
                <a-select-option v-for="item in areaListModal" :key="item.id" :value="item.id">
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </div>
          </a-descriptions-item>
          <a-descriptions-item :span="3">
            <template v-slot:label>
              <div class="contShortwidth">预约天数</div>
            </template>
            <div class="contwidthLon">
              <a-input-number placeholder="请输入预约天数"
                              v-model="modalParams.reservationNumber"
                              :min="1" :precision="0" :formatter="numberRep"
                              :parser="numberRep" style="width: 100%"/>
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </a-spin>
    </a-modal>

  </div>
</template>

<script>
import localezh_CN from 'antd/lib/locale-provider/zh_CN'
import {tableBoxHeight} from "@/api/communal";
import sidebarRole from "@/components/sidebarRole.vue";
import adminsDefinitionApi from "@/api/visitorSystem/adminsDefinition";
import reserveDaysConfigApi from "@/api/visitorSystem/reserveDaysConfig";
import reservationApi from "@/api/reservation";

export default {
  components: {
    sidebarRole
  },
  name: 'adminsDefintion',
  data() {
    return {
      localezh_CN,
      xWidth: '',
      yHeight: '',
      tableData: [],
      pagination: false,
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      columns: [], // 表格表头,

      //查询参数
      query: {
        searchName: null,
        checkIds: [],
        selectId:[],
      },

      //基地列表
      visitBaseName: "全部",   //基地名称
      visitBaseId: 99,   //99查全部，或者基地id
      baceType: [
        {name: "全部", id: 99},
      ],
      baceTypeModal:[],   //弹窗基地名称
      //区域列表
      areaName: "全部",    //区域名称
      visitAreaId: "",   //99查全部，或者区域id
      isHaveDoor: 0,   //是否有门 1有门 ， 0 没有门
      areaList: [
        {areaName: "全部", id: ""},
      ],
      areaListModal:[], //弹窗区域列表

      modalVisible: false,
      modalTitle: "",
      //新增/修改保存按钮loading
      confirmLoading:false,
      modalLoading:false,
      spinning:false,
      //新增修改弹窗提交参数
      modalParams:{
        baseId: undefined,   //基地id ，a-select组件单选时默认 undefined ， 否则输入框不显示默认的 placeholder
        baseName:"",
        areaId: undefined,   //区域id ，可多选
        areaNames:"",
        reservationNumber: 1,
        noarea: false  // true 不需要选区域， false 需要选区域
      },
      isSuper:"",

    }
  },
  beforeMount() {
    this.columns = [
      {
        title: '序号', // 表头
        dataIndex: 'serialNumber', // 字段名称
        width: '50px', // 设列宽度
        align: 'center', // 居中显示
        fixed: "left",
        className: 'changeBack', // 重置覆盖背景色为浅灰色，否则是白色的
        customRender: (value, row, index) => `${index + 1}` // 设置动态序号
      },
      {
        title: '基地',
        dataIndex: 'baseName',
        width: '120px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '区域',
        dataIndex: 'areaName',
        width: '120px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '预约天数',
        dataIndex: 'reservationNumber',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '创建时间',
        dataIndex: 'creationTime',
        width: '150px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '创建人',
        dataIndex: 'creationUserName',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
        width: '150px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '修改人',
        dataIndex: 'updateUserName',
        width: '100px',
        align: 'center',
        ellipsis: true,
        className: 'changeBack'
      },
      {
        title: '',
        dataIndex: '',
        width: 'auto',
        align: 'center',
        className: 'changeBack'
      },
  ]

  },
  created() {

  },
  destroyed() {

  },
  mounted() {
    this.xWidth = this.getTableWidth();
    // this.checkIsSuper();
    this.findRegionList();
    this.searching();
    this.$nextTick(()=>{
      this.yHeight = tableBoxHeight() + 43 + 'px';
      let minHeight = document.getElementsByClassName("ant-table");
      minHeight[0].style.minHeight = tableBoxHeight() + 83 + "px";
    })

  },
  computed:{
    //展示页面复选框
    rowSelection() {
      let _this = this;
      return {
        fixed: true,
        selectedRowKeys:_this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          _this.selectedRowKeys = selectedRowKeys;
          _this.selectedRows = selectedRows;
          // console.log(_this.selectedRowKeys,_this.selectedRows)
        },
        onSelect: (record, selected, selectedRows) => {
          //console.log(record, selected, selectedRows);
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          //console.log(selected, selectedRows, changeRows);
        }
      };
    },
  },
  methods: {

    //查询按钮
    searching() {
      let param={
        baseId: this.visitBaseId,
        areaId: 99
      }
      //查询
      this.loading = true;
      reserveDaysConfigApi.getAccountList(param).then(res=>{
        this.loading = false;
        if (res.data.success) {
          this.selectedRowKeys = [];
          this.selectedRows = [];
          this.tableData = res.data.result;
        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    //查询登陆人是否是超级管理员
    checkIsSuper() {
      adminsDefinitionApi.checkIsSuper().then(res=>{
        // console.log(res);
        if (res.data.success) {
          this.isSuper = res.data.result.isSuper;

        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    // 计算表格宽度
    getTableWidth() {
      let totals = null
      var el
      for (el of this.columns) {
        totals += parseInt(el.width)
      }
      return totals + 100 + 'px'
    },
    //添加/修改账户
    addAccountOk() {
      if (this.modalParams.baseId == undefined){
        this.$message.warning("请选择基地");
        return
      }
      if (!this.modalParams.noarea){
        if (this.modalParams.areaId == undefined){
          this.$message.warning("请选择区域");
          return
        }
      }
      let param = {
        id: this.modalTitle=="新增"?"":this.selectedRows[0].id,
        baseId: this.modalParams.baseId,
        areaId: this.modalParams.noarea?0:this.modalParams.areaId,
        reservationNumber: this.modalParams.reservationNumber
      };
      // console.log(param)
      this.confirmLoading = true;
      this.modalLoading = true;
      reserveDaysConfigApi.addOrUpdateUser(param).then(res=>{
        if (res.data.success) {
          this.$message.success(res.data.message);
          this.addAccountCancel();
          this.searching();
        } else {
          this.confirmLoading = false;
          this.modalLoading = false;
          this.$message.error(res.data.message);
        }
      })
    },
    //取消、关闭弹窗
    addAccountCancel() {
      this.modalLoading = false;
      this.confirmLoading = false;
      this.modalParams.baseId = undefined;
      this.modalParams.baseName = "";
      this.modalParams.areaId = undefined;
      this.modalParams.areaNames = "";
      this.areaListModal = [];
      this.modalParams.reservationNumber = 1;
      this.modalParams.noarea = false;
      this.modalVisible = false;
    },
    //打开新增/修改弹窗
    async openModal(title) {
      // console.log(this.areaListModal);
      this.modalTitle = title;
      if(title=="新增"){
        this.modalVisible = true;
      }else {
        if (this.selectedRows.length == 1) {
          this.modalVisible = true;

          let row = this.selectedRows[0];
          this.modalParams.baseId = row.baseId;
          this.modalParams.reservationNumber = row.reservationNumber;
          // isBase 0 根据基地配置 1根据区域配置 预约天数
          if (row.isBase == 0) {
            this.modalParams.noarea = true;
            this.modalParams.areaId = undefined;
            this.modalParams.areaNames = "";
          } else {
            this.modalParams.noarea = false;
            this.modalLoading = true;
            await this.getAreaList(2);
            this.modalLoading = false;
            this.modalParams.areaId = row.areaId;
          }
        } else{
          this.$message.warning("请选择一条要修改的数据");
          return
        }
      }
    },
    //删除管理员
    dateleUser() {
      let _this = this;
        if(null!=this.selectedRowKeys && this.selectedRowKeys.length>0){
          this.$confirm({
            title: '删除确认',
            content: '确定要删除已勾选的管理员账户吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
              let param = {
                ids:_this.selectedRowKeys.join()
              };
              _this.spinning = true;
              return reserveDaysConfigApi.deleteAccount(param).then(res=>{
                _this.spinning = false;
                if (res.data.success) {
                  _this.$message.success(res.data.message);
                  _this.searching();
                } else {
                  _this.$message.error(res.data.message);
                }
              })
            },
          });
        }else{
          this.$message.warning("请勾选需要删除的数据");
        }
    },
    roleMainTreeSelect(v){
      // console.log(v);
      this.query.selectId = v;
      this.searching();
    },
    selectRow(record){
        return {
          props: {

          },
          on: { // 事件
            click: (event) => {
              if(this.selectedRowKeys.indexOf(record.id) > -1){
                this.selectedRows = this.selectedRows.filter(v=>{
                  return v.id!=record.id
                })
                this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record.id),1)
              }else{
                this.selectedRows.push(record)
                this.selectedRowKeys.push(record.id)
              }
            },       // 点击行
            dblclick: (event) => {
            },
            contextmenu: (event) => {
            },
            mouseenter: (event) => {
            },  // 鼠标移入行
            mouseleave: (event) => {
            }
          },
        }
    },
    setRowClassName(record){
      return this.selectedRowKeys.indexOf(record.id) > -1 ? 'clickRowStyl' : '';
    },
    // 获取基地信息
    async findRegionList() {
      let resp = await reservationApi.getBdSysItemList({typeId: 200});
      // console.log(resp);
      if (resp.data.success) {
        this.baceType = [...this.baceType, ...resp.data.result];
        this.baceTypeModal = resp.data.result;
      } else {
        this.$message.error(resp.data.message);
      }
    },
    // 获取区域
    async getAreaList(num) {
      // num 1 主页面的请求 2弹窗的请求
      let res = await reservationApi.getBdVisitAreaListByRoleNew({typeId: num == 1?this.visitBaseId:this.modalParams.baseId})
      // console.log(res.data);
      if (res.data.success) {
        this.areaListModal = [];
        if (num == 1){
          this.areaList = [{areaName: "全部", id: ""}];
          this.areaList = [...this.areaList, ...res.data.result];
        } else {
          this.areaListModal = res.data.result;
        }
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 弹窗切换基地，单选
    handleChangeBase(e){
      // console.log(e);
      let names = "",that = this,selectItem = {};
      that.baceTypeModal.forEach(el=>{
        if (e == el.id){
          names = el.name;
          selectItem = el;
        }
      })
      // console.log(selectItem);
      // isBase 0 根据基地配置 1根据区域配置 预约天数
      if (selectItem.isBase == 0){
        this.modalParams.noarea = true;
      } else {
        this.modalParams.noarea = false;
      }
      this.modalParams.baseId = e;
      this.modalParams.baseName = names;
      this.modalParams.areaId = undefined;
      this.modalParams.areaNames = "";
      this.getAreaList(2);
    },
    // 弹窗切换区域，多选
    handleChangeArea(e){
      // console.log(e);
      let names = "",that = this;
      // 多选
      // e.forEach(key=>{
      //   that.areaListModal.forEach(el=>{
      //     if (key == el.id){
      //       names.push(el.areaName)
      //     }
      //   })
      // })
      // 单选
      that.areaListModal.forEach(el=>{
        if (e == el.id){
          names = el.areaName;
        }
      })
      this.modalParams.areaId = e;
      this.modalParams.areaNames = names;
    },
    //只能输入整数,有字母或汉字返回空
    numberRep(value){
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, '') : 1
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, '') : 1
      } else {
        return 1
      }
    },
    // 切换基地，选择基地
    baseMenuClick(e) {
      this.baceType.filter(el => {
        if (el.id == e.key) {
          this.visitBaseName = el.name;
          this.visitBaseId = el.id;
        }
      });
    },

  },
}
</script>
<style>
.clickRowStyl{
  background-color:#D8E6DF !important
}
.ant-table-tbody>.clickRowStyl>td{
  background-color:#D8E6DF !important
}
</style>
